﻿<%@ Page Language="c#" ContentType="text/html" ResponseEncoding="utf-8" Async="true" MasterPageFile="~/administration/list_private.master" Inherits="ACM.cmsarea08.Administration.Core.gesHomePage" %>
<%@ MasterType VirtualPath="~/administration/list_private.master" %>
<asp:Content ID="PageBody" Runat="server" ContentPlaceHolderID="MasterBody">
<style type="text/css">
	.dragitem { font-size:11px; width:60px; height:60px; text-align:center; padding:5px; border:1px solid #666666; margin:5px 5px; background:#e2e3e0; float:left; }
	.artitem { display:block; width:auto; height:auto; }
	.cestino { font-size:11px; width:80px; height:80px; text-align:center; float:right; border:1px solid #666666; margin:5px 5px; background:#e2e3e0 url(../template/img/cestino.png) no-repeat; }
	#draggables { text-align:center; }
	#homepagecc { display:block; }
	.sortme {	padding: 4px 8px;
				color: #fff;
				cursor: pointer;
				list-style: none;
				width: 300px;
				background-color: #222;
				margin:1px;
			}
	.itemlist {
		margin:2px; float:right; width:37%; border:1px solid #666666;  min-height:150px; padding:5px;
	}
	.itemlist h3 { margin:2px; padding:0px; }
</style>
<div class="dynform dfbody dfmainbody">
<h1><img src="../template/admimg/hp_big.jpg" alt="User Forms Manager" />Gestione HomePage</h1>
<!-- modello per la gestione -->
<!-- zona dinamica -->
<div style="clear:both;">
<input type="button" value="salva" id="salva_btm" />
<input type="button" value="azzera" id="azzera_btm" />
<input type="button" value="generea codice template" id="tmp_btm" />
<div style=" margin:2px; float:left; width:58%; border:2px solid #666666; background:#e2e3e0; min-height:150px; padding:5px;">
	<div id="cestino" class="cestino">cestino</div>elementi homepage:
    <ul id="homepagecc">
        <li class="sortme">0</li>
        <li class="sortme">1</li>
        <li class="sortme">2</li>
        <li class="sortme">3</li>
        <li class="sortme">4</li>
        <li class="sortme">5</li>    	
    </ul>
    
</div>
<div class="itemlist" >
	<h3>Elementi Disponibili</h3>
    <div style="clear:both;">
        <select id="elementi" name="elementi">
        <option value="-1">-- scegli --</option>
        <option value="0">Moduli</option>
        <option value="1">Blocchi Visivi</option>    
        <option value="2">Contenuti</option>        
        </select>
		<div id="choices">&nbsp;
        </div>
    </div>
	<div style="clear:both;" id="draggables">
    	<div class="dragitem">body control</div>
        <div class="dragitem">component control</div>
    
    </div>
    
</div>
<input type="text" value="" id="txtsalva"  />
<br class="clearbr"/>
</div>
<br class="clearbr"/>
</div>
<script language="javascript">
//init valori:
window.addEvent('domready', function() {
	var src_home 	= "homepagecc";
	var src_item 	= "draggables";
	var src_select 	= "elementi";
	var btmsalva 	= "salva_btm";
	var btmazzera 	= "azzera_btm";	
	var btmtmp 	= "tmp_btm";		
	var salvatxt 	= "txtsalva";	
	var currentLayout = "";
	//var temporanea
	var cur_scelta = "-1";
	var saved = true;
	
	//avvia sortable 1:
//	var fxsort = $('homepagecc').tween('background-color', {wait: false});
//	var fxcestino = $('cestino').tween('background-color', {wait: false});	
	var fxsort = $('homepagecc').get('tween', 'background-color', {duration: 200});
	var fxcestino = $('cestino').get('tween', 'background-color', {duration: 200});
	
	var sortPage = null;
	
	$(btmsalva).addEvent('click', function () {
		if( $(salvatxt) && sortPage!=null) {
			var resulta = "";
			var elementi = sortPage.elements;
			elementi.each(function(element, i){
				var relo = element.getAttribute('rel');
				resulta += (relo?relo:element.innerHTML) + '~' + element.innerHTML+ ',';
			});
			resulta = '[' + resulta.substring(0,resulta.length-1) + ']';
			$(salvatxt).setAttribute('value',resulta);
			//fai la request in post.
			var myRequest = new Request(
				{
					method: 'get', 
					url: '/administration/core/xml_server.asmx/setHomePageLayout',	
					onSuccess: function(req,xml) {
						if (window.ActiveXObject)
						{
							var xmlObj=new ActiveXObject("Microsoft.XMLDOM");
							xmlObj.async="false";
							xmlObj.loadXML(req);
							if(xmlObj.documentElement == null) {	/*alert('sono nullo');*/ return; }
							cXml = xmlObj.documentElement;		
						} else {
							cXml = xml.documentElement;
						}
						if(cXml == null) { /*alert('cXml nullo....');*/ return; }		
						var child = cXml.firstChild;
						if(parseInt(child.nodeValue)>0) {
							alert('ok salvato');
							CaricaLayout();
							saved=true;
						} else
							alert('impossibile salvare.');
					}					
					
					
				}
			).send('newlayout=' + resulta);	
			
		}
	});
	$(btmazzera).addEvent('click', function () {
		CaricaLayout();
		saved = true;
	});
	
	$(btmtmp).addEvent('click', function () {
		if(!saved) { alert('devi salvare prima di generare il codice per il template.'); return; }
		if(sortPage==null) {  alert('ci sono problemi con i dati, ricarica la pagina.'); return; }
		var elemento = new Element('textarea');
		elemento.setProperty('id','prevHP');
		elemento.setStyles( { 'width': 450, 'height' : 550, 'border' :'1px solid #e2e3e0','font-size':'11px' }).injectInside(document.body);
		var resulta = "";
		var elementi = sortPage.elements;
		resulta ="<!-- put your layout html here -->\n";
		elementi.each(function(element, i){
			resulta += '\n<!-- put your item ' +i+' layout html here (before item) -->\n';
			resulta += "<item>" + i + "</item><!-- code for item: "+element.innerHTML+ ' -->\n';
			resulta += '<!-- put your item ' +i+' layout html here (after item) -->\n';	
		});		
		resulta +="\n<!-- put your layout html here -->\n";
		elemento.set('html',resulta);
		showModalInline('Homepage Template','prevHP','500','450');
		elemento.dispose();
	});
	
	function InitSortabile() {
			sortPage = new Sortables($(src_home), {
				cloneOpacity:.2,
				handle: 'li',
				ghost: false,
				initialize: function(){
					this.elements.each(function(element, i){	
						
						element.addEvent('mousedown', function(e) {				
							e = new Event(e).stop();
							var clone = this.clone()
							.setStyles(this.getCoordinates()) 
							.setStyles({'opacity': 0.7, 'position': 'absolute'})
							.addEvents({
										'emptydrop': function() {
											this.removeEvents();
											this.dispose();
										},
										'dropped': function(droppable){
											try {
											if(sortPage) {
												sortPage.removeItems(element);
												
												if(!sortPage.elements || sortPage.elements.length==0) {
													var emp = new Element('li').addClass('sortme');
													emp.set('html','no items');
													emp.setProperty('id','emptyhp');
													emp.setProperty('rel','empty');													
													$(src_home).adopt(emp);
													sortPage.addItems(emp);
												}												
											}
												
											element.removeEvents();
											element.dispose();
											} catch (errore) {

											}
											saved = false;	
											droppable.tween('background-color','#e2e3e0');										
										}
									}).injectInside(document.body); 							
							
							
							var drag = clone.makeDraggable({
								droppables: $('cestino'),
								onLeave : function(el,droppable) {
									if(droppable)
										droppable.tween('background-color','#e2e3e0');
								},
								onDrop : function(el,droppable) {
									if(droppable) {
										droppable.tween('background-color','#000099');
										el.fireEvent('dropped', droppable);
									}
									el.removeEvents();				
									el.dispose();
							
								},
								onEnter : function(el,droppable) {
									if(droppable)
										droppable.tween('background-color','#000099');
								}
							}); 
							drag.start(e); 							
					
						});
					});
				}
			});
			
			//eventi del cestino
			$('cestino').removeEvents();
	}

	function Azzera() {
		//choices
		//draggables
		$('choices').empty();
		$('draggables').empty();
	};
	
	function ImpostaDrops() {
		$$('#draggables .dragitem').each(function(elemento){
				elemento.addEvent('mousedown', function(e) {
							e = new Event(e).stop();
							var clone = this.clone()
								.setStyles(this.getCoordinates()) // this returns an object with left/top/bottom/right, so its perfect
								.setStyles({'opacity': 0.7, 'position': 'absolute'})
								.addEvents({
									'emptydrop': function() {
										this.removeEvents();
										this.dispose();
									},
									'dropped': function(droppable){
										//item.injectInside(droppable);
									}
								}).injectInside(document.body);
							
							var drag = clone.makeDraggable({
								droppables: $(src_home),
								onEnter : function(el,droppable) {
									if(!window.ie) {
										droppable.tween('background-color', '#7389AE');
									} else
										droppable.setStyle('background-color','7389AE');								
								},								
								onDrop : function(el,droppable) {
									if(!window.ie) {
										droppable.tween('background-color', '#e2e3e0');
									} else
										droppable.setStyle('background-color','e2e3e0');

									var testo = el.innerHTML;
									var relo = el.getAttribute('rel');
									var sortmio = new Element('li').addClass('sortme').set('html',testo);
									if(relo)
										sortmio.setAttribute('rel',relo);
									el.fireEvent('dropped', this);
									el.removeEvents();					
									el.dispose();
									//verifica figli in disortmio e casomai elimina.
									var checkFigli = $$('#' +src_home + ' li');
									if( checkFigli.length > 0 ) {
										if(checkFigli.length == 1) {
											if(checkFigli[0].getAttribute('rel')=='empty' ) {
												checkFigli[0].removeEvents();
												checkFigli[0].dispose();	
																						
											}
										}
									}
									droppable.adopt(sortmio);
									//riavvia sort.
									saved = false;
									InitSortabile();
								},
								onLeave : function(el,droppable) {
									if(window.ie) droppable.setStyle('background-color','#e2e3e0');
									else droppable.tween('background-color', '#e2e3e0'); 
								}
							}); // this returns the dragged element
							drag.start(e); // start the event manual
						});
				});
				
				$(src_home).removeEvents();
	}
	
	function initCategorie(container) {
		if(container.value==-1) {
			if( $('mio_cat') ) Element.remove($('mio_cat'));
			$('draggables').empty();
			return;
		}
		if( $('mio_cat')     ) {
			Element.remove($('mio_cat'));
			$('draggables').empty();
		}
		var mio_cat = new Element('select').setProperty('id', 'mio_cat').injectInside( $('choices') );
		new Element('option').setProperty('value','-1').set('html','-- categorie --').injectInside( mio_cat );
			var myRequest = new Request(
				{
					method: 'get', 
					url: '/administration/core/xml_server.asmx/getCategory',			
					onSuccess: function(req,xml) {
						var filez = DecodeAjax(req,xml,'Table');
						for (i=0;i<filez.length;i++)
						{	
							//1 id , 3 titolo
							var test_ti = ""; //xml_table.childNodes[3].firstChild.nodeValue;
							var test_di = ""; //xml_table.childNodes[1].firstChild.nodeValue;
							for(var c = 0 ; c<filez[i].childNodes.length; c++) {
								if(  filez[i].childNodes[c].nodeName != '#text') {
									//getNoodeValue:
									if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='id' )
										test_di = GetNodeValue( filez[i].childNodes[c] );
									if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='titolo' )
										test_ti = GetNodeValue( filez[i].childNodes[c] );
								}							
							}
							new Element('option').setProperty('value',test_di).set('html',test_ti).injectInside(mio_cat );
						}					
					}	
				}
			).send('idsec=' + container.value);
		//appendi evento:
		mio_cat.addEvent('change', function() {
			if(this.value=="-1") return;
			$('draggables').empty();
			//attiva drop:
			var myRequest = new Request(
				{
					method: 'get', 
					url: '/administration/core/xml_server.asmx/getArticoli',
					onSuccess: function(req,xml) {
							var filez = DecodeAjax(req,xml,'Table');
							for (i=0;i<filez.length;i++)
							{	
								//1 id , 3 titolo
								var test_ti = ""; //xml_table.childNodes[3].firstChild.nodeValue;
								var test_di = ""; //xml_table.childNodes[1].firstChild.nodeValue;
								for(var c = 0 ; c<filez[i].childNodes.length; c++) {
									if(  filez[i].childNodes[c].nodeName != '#text') {
										//getNoodeValue:
										if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='id' )
											test_di = GetNodeValue( filez[i].childNodes[c] );
										if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='titolo' )
											test_ti = GetNodeValue( filez[i].childNodes[c] );
									}							
								}
								var pin = new Element('div').setProperty('class','dragitem artitem').set('html',test_ti).injectInside( $('draggables') );
								pin.setAttribute('rel',"CT~" + test_di);
							}	
							ImpostaDrops();
					}					
				}
			).send('idcat=' + this.value);
//			new Element('div').setProperty('class','dragitem').set('html','art v1_' + this.value).injectInside( $('draggables') );
//			new Element('div').setProperty('class','dragitem').set('html','art v2_' + this.value).injectInside( $('draggables') );
			ImpostaDrops();
		});
	}

	function Carica(scelta) {
		//scelta 0 --> moduli
		if(scelta=='0') {
			var sel_mod = new Element('select').setProperty('id', 'choose_mod').injectInside( $('choices') );
			sel_mod.addEvent('change',function() { 
							//load elementi:
							$('draggables').empty();
							if(this.value==-1) return;
							//ottieni configurazione ed elemento body, o compo
							///administration/core/xml_server.asmx/getModulesElement?idmod=string
							var valore = this.value;
							var testo  = "";
							for(var i = 0;i<this.options.length;i++) {
								if(this.options[i].selected) {
									testo = this.options[i].innerHTML;
									break;
								}
							}
							var myRequest = new Request(
								{
									method: 'get', 
									url: '/administration/core/xml_server.asmx/getModulesElement',	
									onSuccess: function(req,xml) {
										var filez = DecodeAjax(req,xml,'Table');
										for (i=0;i<filez.length;i++)
										{	
											//1 id , 3 titolo
											var mbody="";
											var mcontrol ="";
											for(var c = 0 ; c<filez[i].childNodes.length; c++) {
												if(  filez[i].childNodes[c].nodeName != '#text') {
													//getNoodeValue:
													if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='body' )
														mbody = GetNodeValue( filez[i].childNodes[c] );
													if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='control' )
														mcontrol = GetNodeValue( filez[i].childNodes[c] );
												}							
											}
											if(mbody!="") {
													var bd = new Element('div').setProperty('class','dragitem').set('html',testo+ ' body control').injectInside( $('draggables') );
													bd.setAttribute('rel','MDB~' + valore);
											}
											if(mcontrol!="") {
													var bc = new Element('div').setProperty('class','dragitem').set('html',testo+ ' control').injectInside( $('draggables') );
													bc.setAttribute('rel','MDC~' + valore);
												}
										}
										ImpostaDrops();
									}									
									
								}
							).send('idmod='+this.value);						
//							new Element('div').setProperty('class','dragitem').set('html','body control ' + this.value).injectInside( $('draggables') );
//							new Element('div').setProperty('class','dragitem').set('html','component control ' + this.value).injectInside( $('draggables') );
							//init drag.
//							ImpostaDrops();
						 });
			//ottieni elementi ajax per sel_mod...
			new Element('option').setProperty('value','-1').set('html','-- scegli modulo --').injectInside( sel_mod );
			var myRequest = new Request(
				{
					method: 'get', 
					url: '/administration/core/xml_server.asmx/getModules',			
					onSuccess: function(req,xml) {
						var filez = DecodeAjax(req,xml,'Table');
						for (i=0;i<filez.length;i++)
						{	
							//1 id , 3 titolo
							var test_ti = ""; //xml_table.childNodes[3].firstChild.nodeValue;
							var test_di = ""; //xml_table.childNodes[1].firstChild.nodeValue;
							for(var c = 0 ; c<filez[i].childNodes.length; c++) {
								if(  filez[i].childNodes[c].nodeName != '#text') {
									//getNoodeValue:
									if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='id' )
										test_di = GetNodeValue( filez[i].childNodes[c] );
									if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='titolo' )
										test_ti = GetNodeValue( filez[i].childNodes[c] );
								}							
							}
							new Element('option').setProperty('value',test_di).set('html',test_ti).injectInside(sel_mod );
						}	
					}
									
				}
			).send();
			
			return;
		}
		//scelta 1 --> bv;
		if(scelta=='1') {
			$('draggables').empty();
			//--/administration/core/xml_server.asmx/getBlockViews
			var myRequest = new Request(
				{
					method: 'get', 
					url: '/administration/core/xml_server.asmx/getBlockViews',		
					onSuccess: function(req,xml) {
						var filez = DecodeAjax(req,xml,'Table');
						for (i=0;i<filez.length;i++)
						{	
							//1 id , 3 titolo
							var test_ti = ""; //xml_table.childNodes[3].firstChild.nodeValue;
							var test_di = ""; //xml_table.childNodes[1].firstChild.nodeValue;
							for(var c = 0 ; c<filez[i].childNodes.length; c++) {
								if(  filez[i].childNodes[c].nodeName != '#text') {
									//getNoodeValue:
									if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='id' )
										test_di = GetNodeValue( filez[i].childNodes[c] );
									if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='titolo' )
										test_ti = GetNodeValue( filez[i].childNodes[c] );
								}							
							}
							var uno  = new Element('div').setProperty('class','dragitem').set('html',test_ti).injectInside( $('draggables') );
							uno.setAttribute('rel', 'BV~' +test_di);
						}				
						ImpostaDrops();
					}					
					
				}
			).send();			
			
			return;
		}
		//scelta 2 --> contenuti
		if(scelta=='2') {
			var sec_mod = new Element('select').setProperty('id', 'choose_sec').injectInside( $('choices') );
			//aggiungo le opzioni
			new Element('option').setProperty('value','-1').set('html','-- scegli sezione').injectInside( sec_mod );

			var myRequest = new Request(
				{
					method: 'get', 
					url: '/administration/core/xml_server.asmx/getSection',	
					onSuccess: function(req,xml) {
						var filez = DecodeAjax(req,xml,'Table');
						for (i=0;i<filez.length;i++)
						{	
							//1 id , 3 titolo
							var test_ti = ""; //xml_table.childNodes[3].firstChild.nodeValue;
							var test_di = ""; //xml_table.childNodes[1].firstChild.nodeValue;
							for(var c = 0 ; c<filez[i].childNodes.length; c++) {
								if(  filez[i].childNodes[c].nodeName != '#text') {
									//getNoodeValue:
									if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='id' )
										test_di = GetNodeValue( filez[i].childNodes[c] );
									if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='titolo' )
										test_ti = GetNodeValue( filez[i].childNodes[c] );
								}							
							}
							new Element('option').setProperty('value',test_di).set('html',test_ti).injectInside(sec_mod );
						}
					}					
					
				}
			).send();
								
			sec_mod.addEvent('change',function() {
				//sto dentro
				if(this.value==-1) return;
				initCategorie(this);
			});
			//ottieni elementi ajax per sel_mod...
			return;
		}
	
	
	}
	
	
	var cambioScelta = function() {
		if(cur_scelta != this.value)  {
			//alert('nuova scelta' + this.value);
			cur_scelta = this.value;
			Azzera();
			Carica(cur_scelta);
		}
	};	
	
	function NoLayout() {
		$(src_home).empty();
		var empty = new Element('li').set('html',"empty").injectInside( $(src_home) );
		empty.setAttribute('rel','empty');
	}
	
	function CaricaLayout() {
		//richiedi layout. - ottieni l'elenco e compila la stringa di input.
		//svuota  --> getHomePageLayout
		NoLayout();
		
		//load

		var myRequest = new Request(
			{
				method: 'get', 
				url: '/administration/core/xml_server.asmx/getHomePageLayout',	
				onSuccess: function(text,xml) {
						if (window.ActiveXObject)
						{
							var xmlObj=new ActiveXObject("Microsoft.XMLDOM");
							xmlObj.async="false";
							xmlObj.loadXML(text);
							if(xmlObj.documentElement == null) {	/*alert('sono nullo');*/ return; }
							cXml = xmlObj.documentElement;		
						} else {
							cXml = xml.documentElement;
						}
						if(cXml == null) { /*alert('cXml nullo....');*/ return; }
						var filez = cXml.getElementsByTagName('Table');	
						$(src_home).empty();
						for (i=0;i<filez.length;i++) {
								var itype = "";
								var iid   = "";
								var ititle = "";
								for(var c = 0 ; c<filez[i].childNodes.length; c++) {
									if(  filez[i].childNodes[c].nodeName != '#text') {
										//getNoodeValue:
//										if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='id' )
//											iid = GetNodeValue( filez[i].childNodes[c] );
										if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='itemtype' )
											itype = GetNodeValue( filez[i].childNodes[c] );
										if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='itemid' )
											iid = GetNodeValue( filez[i].childNodes[c] );
										if( filez[i].childNodes[c].nodeName.toString().toLowerCase()=='titolo' )
											ititle = GetNodeValue( filez[i].childNodes[c] );
									}
								}		
								if(itype!="" && iid!="") {
									var lio =  new Element('li').setProperty('class','sortme').set('html',ititle).injectInside($(src_home) );
									lio.setAttribute('rel', itype + '~' + iid);
								}																					
						
						}
						if( $$('#'+src_home + ' li').length==0 ) {
							NoLayout();
						} else InitSortabile();
				} ,
				onFailure : function() {
					NoLayout();
				}				
			}
		).send();		

	}	
	
	//avvia handler per i loader:
	var selettore = $(src_select);
	selettore.addEvent('change',cambioScelta);
	//avvia sort:
	CaricaLayout();
	InitSortabile();
	Azzera();
	
	
});

function GetNodeValue(xmlnode) {
	if(xmlnode.childNodes.length>0)
		return xmlnode.firstChild.nodeValue;
	else
		return "";
}

function DecodeAjax(text,xml,tablename) {
	if (window.ActiveXObject)
	{
		var xmlObj=new ActiveXObject("Microsoft.XMLDOM");
		xmlObj.async="false";
		xmlObj.loadXML(text);
		if(xmlObj.documentElement == null) {	/*alert('sono nullo');*/ return; }
		cXml = xmlObj.documentElement;		
	} else {
		cXml = xml.documentElement;
	}
	if(cXml == null) { /*alert('cXml nullo....');*/ return; }
	var filez = cXml.getElementsByTagName(tablename);	
	return filez;
}
</script>

</asp:content>